<template>
  <div class="forget-password-page">
    <!-- 动态背景 -->
    <div class="background">
      <canvas class="particle-canvas"></canvas>
      <div class="floating-shapes">
        <div style="width: 150px; height: 150px; top: 10%; left: 5%"></div>
        <div style="width: 100px; height: 100px; top: 60%; left: 80%"></div>
        <div style="width: 120px; height: 120px; top: 30%; left: 70%"></div>
      </div>
    </div>

    <div class="container">
      <div class="forget-password-card">
        <h2 class="title">忘记密码</h2>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
        <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

        <!-- 第一步：选择方式并提交校验材料（验证码或人脸） -->
        <div v-if="currentStep === 1" class="form-container">
          <div class="form-group">
            <label for="identifier">账户 (手机号/邮箱)</label>
            <input 
              type="text" 
              id="identifier" 
              v-model="identifier" 
              placeholder="请输入您的账户" 
              required 
            />
          </div>

          <!-- 重置方式选择（使用 uni-app picker） -->
          <div class="form-group">
            <label>重置方式</label>
            <picker :range="resetTypeOptions" :value="resetTypeIndex" @change="onResetTypePickerChange">
              <div class="uni-input">{{ resetTypeOptions[resetTypeIndex] }}</div>
            </picker>
          </div>

          <div class="form-group">
            <label for="code">验证码</label>
            <div class="code-group">
              <input 
                type="text" 
                id="code" 
                v-model="code" 
                placeholder="请输入验证码" 
                maxlength="6"
                :disabled="resetType !== 'code'"
              />
              <button 
                class="send-code-btn" 
                @click="sendCode" 
                :disabled="isCodeSending || !identifier || resetType !== 'code'"
              >
                {{ codeBtnText }}
              </button>
            </div>
          </div>

          <!-- 人脸验证（仅在人脸方式下显示） -->
          <div class="form-group" v-if="resetType === 'face'">
            <label>人脸验证</label>
            <div class="face-recognition">
              <div class="action-prompt" v-if="currentAction">
                <div class="action-icon" :class="currentAction">
                  <text v-if="currentAction === 'shake_head'">摇头</text>
                  <text v-else-if="currentAction === 'open_mouth'">张嘴</text>
                  <text v-else-if="currentAction === 'blink_eye'">眨眼</text>
                </div>
                <text>{{ actionDescription }}</text>
                <text class="recording-status" v-if="isRecording">正在录制... {{ recordingTime }}s</text>
              </div>

              <!-- #ifdef H5 -->
              <div id="video-container" class="video-container" v-if="isCameraActive"></div>
              <!-- #endif -->

              <!-- #ifdef APP-PLUS || MP-WEIXIN -->
              <camera
                v-if="isCameraActive"
                device-position="front"
                flash="off"
                @error="uni.showToast({ title: '摄像头错误', icon: 'none' })"
                style="width: 100%; height: 300px;"
              ></camera>
              <!-- #endif -->

              <div class="face-buttons">
                <button type="button" @click="toggleCamera">{{ isCameraActive ? '关闭摄像头' : '开启摄像头' }}</button>
                <button type="button" @click="startRecording" :disabled="!isCameraActive || isRecording">开始录制</button>
                <button type="button" @click="getNewAction" :disabled="!isCameraActive">更换动作</button>
              </div>
              <div v-if="recordedFrames.length > 0" class="recording-preview">
                <text>已录制 {{ recordedFrames.length }} 帧</text>
              </div>
            </div>
          </div>

          <button 
            class="next-btn" 
            @click="goNext"
            :disabled="!canGoNext"
          >
            下一步
          </button>
        </div>

        <!-- 第二步：重置密码 -->
        <div v-if="currentStep === 2" class="form-container">
          <div class="form-group">
            <label for="newPassword">新密码</label>
            <input 
              type="password" 
              id="newPassword" 
              v-model="newPassword" 
              placeholder="请输入新密码" 
              required 
            />
          </div>

          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input 
              type="password" 
              id="confirmPassword" 
              v-model="confirmPassword" 
              placeholder="请再次输入新密码" 
              required 
            />
            <span v-if="passwordError" class="field-error">{{ passwordError }}</span>
          </div>

          <button 
            class="reset-btn" 
            @click="resetPassword" 
            :disabled="!newPassword || !confirmPassword || newPassword !== confirmPassword"
          >
            重置密码
          </button>
          
          <button class="back-btn" @click="goBack">
            返回上一步
          </button>
        </div>

        <div class="links">
          <text @click="goToLogin">返回登录</text>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, onMounted, onUnmounted, watch, computed } from "vue";

// 表单数据
const identifier = ref("");
const code = ref("");
const newPassword = ref("");
const confirmPassword = ref("");

// 状态控制
const currentStep = ref(1);
const errorMessage = ref("");
const successMessage = ref("");
const passwordError = ref("");
const isCodeSending = ref(false);
const codeBtnText = ref("发送验证码");
let codeTimer = null;

// 摄像头相关
const videoElement = ref(null);
const isCameraActive = ref(false);
const stream = ref(null);
// 人脸录制相关
const isRecording = ref(false);
const recordingTime = ref(0);
const recordedFrames = ref([]);
const recordingInterval = ref(null);
const frameCaptureInterval = ref(null);
const currentAction = ref('');
const actionDescription = ref('');

// 重置方式（picker）
const resetType = ref('code');
const resetTypeOptions = ['验证码重置', '人脸识别重置'];
const resetTypeIndex = ref(0);
const onResetTypePickerChange = (e) => {
  resetTypeIndex.value = e.detail.value;
  resetType.value = resetTypeIndex.value == 0 ? 'code' : 'face';
  // 切换方式时清理错误/状态
  errorMessage.value = '';
  successMessage.value = '';
};
const canGoNext = computed(() => {
  if (!identifier.value) return false;
  if (resetType.value === 'code') return !!code.value;
  if (resetType.value === 'face') return recordedFrames.value.length >= 5 && !!currentAction.value;
  return false;
});

const startCamera = async () => {
  try {
    // #ifdef H5
    const mediaStream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'user' },
      audio: false
    });
    stream.value = mediaStream;

    const container = document.getElementById('video-container');
    if (videoElement.value) {
      container.removeChild(videoElement.value);
    }

    const video = document.createElement('video');
    video.autoplay = true;
    video.muted = true;
    video.playsInline = true;
    video.style.width = '100%';
    video.style.maxWidth = '100%';
    video.style.height = '250px';
    video.style.background = 'black';
    video.style.objectFit = 'cover';
    video.style.borderRadius = '16px';
    video.style.marginBottom = '16px';
    video.style.boxShadow = '0 4px 20px rgba(0,0,0,0.15)';

    video.srcObject = mediaStream;
    container.appendChild(video);
    videoElement.value = video;
    isCameraActive.value = true;
    // #endif

    // #ifdef APP-PLUS || MP-WEIXIN
    const context = uni.createCameraContext();
    if (context) {
      isCameraActive.value = true;
    }
    // #endif
  } catch (error) {
    console.error('摄像头访问失败:', error);
    uni.showToast({
      title: '摄像头权限被拒绝或设备不支持',
      icon: 'none'
    });
    isCameraActive.value = false;
  }
};

const toggleCamera = async () => {
  if (isCameraActive.value) {
    stopCamera();
  } else {
    await startCamera();
  }
};

const startRecording = () => {
  if (!isCameraActive.value) return;
  isRecording.value = true;
  recordingTime.value = 0;
  recordedFrames.value = [];

  // 计时3秒
  recordingInterval.value = setInterval(() => {
    recordingTime.value++;
    if (recordingTime.value >= 3) {
      stopRecording();
    }
  }, 1000);

  // 采集帧
  frameCaptureInterval.value = setInterval(() => {
    captureFrame();
  }, 200);
};

const captureFrame = () => {
  // #ifdef H5
  if (videoElement.value) {
    const video = videoElement.value;
    if (video.videoWidth && video.videoHeight) {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      if (context) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const base64 = canvas.toDataURL('image/jpeg', 0.8);
        recordedFrames.value.push(base64);
      }
    }
  }
  // #endif

  // #ifdef APP-PLUS || MP-WEIXIN
  const cameraContext = uni.createCameraContext();
  if (cameraContext) {
    cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        uni.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: 'base64',
          success: (fileRes) => {
            const base64 = 'data:image/jpeg;base64,' + fileRes.data;
            recordedFrames.value.push(base64);
          }
        })
      }
    });
  }
  // #endif
};

const stopRecording = () => {
  isRecording.value = false;
  if (recordingInterval.value) clearInterval(recordingInterval.value);
  if (frameCaptureInterval.value) clearInterval(frameCaptureInterval.value);
  if (recordedFrames.value.length < 5) {
    uni.showToast({ title: '录制时间太短，请重试', icon: 'none' });
    recordedFrames.value = [];
  }
};

const stopCamera = () => {
  // #ifdef H5
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
    stream.value = null;
  }
  // #endif
  isCameraActive.value = false;
};

// 发送验证码
const sendCode = async () => {
  if (!identifier.value) {
    uni.showToast({
      title: '请输入您的手机号或邮箱',
      icon: 'none'
    });
    return;
  }

  try {
    isCodeSending.value = true;
    codeBtnText.value = "发送中...";
    
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: "${NETWORK_CONFIG.API_BASE_URL}/auth/forget-password/send-code",
        method: "POST",
        header: { "Content-Type": "application/json" },
        data: { identifier: identifier.value },
        success: (res) => {
          resolve({
            ok: res.statusCode >= 200 && res.statusCode < 300,
            statusCode: res.statusCode,
            data: res.data
          });
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
    
    if (response.ok) {
      successMessage.value = "验证码已发送，请查收";
      errorMessage.value = "";
      
      uni.showToast({
        title: '验证码已发送，五分钟内有效',
        icon: 'success'
      });
      
      // 倒计时
      let countdown = 60;
      codeBtnText.value = `已发送(${countdown}s)`;
      
      if (codeTimer) clearInterval(codeTimer);
      
      codeTimer = setInterval(() => {
        countdown--;
        codeBtnText.value = `已发送(${countdown}s)`;
        
        if (countdown <= 0) {
          clearInterval(codeTimer);
          codeBtnText.value = "发送验证码";
          isCodeSending.value = false;
        }
      }, 1000);
    } else {
      errorMessage.value = response.data.message || "验证码发送失败";
      successMessage.value = "";
      isCodeSending.value = false;
      codeBtnText.value = "发送验证码";
      
      uni.showToast({
        title: response.data.message || '验证码发送失败',
        icon: 'none'
      });
    }
  } catch (error) {
    errorMessage.value = "发送验证码时出错: " + error.message;
    successMessage.value = "";
    isCodeSending.value = false;
    codeBtnText.value = "发送验证码";
    
    uni.showToast({
      title: '发送验证码失败',
      icon: 'none'
    });
  }
};

// 第一步完成，进入第二步
const goNext = () => {
  if (!identifier.value) {
    uni.showToast({ title: '请输入账户', icon: 'none' });
    return;
  }
  if (resetType.value === 'code') {
    if (!code.value) {
      uni.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }
  } else if (resetType.value === 'face') {
    if (recordedFrames.value.length < 5 || !currentAction.value) {
      uni.showToast({ title: '请按提示完成人脸录制', icon: 'none' });
      return;
    }
  }
  errorMessage.value = '';
  successMessage.value = '';
  currentStep.value = 2;
  uni.showToast({ title: '验证材料已就绪，请设置新密码', icon: 'success' });
};

// 重置密码
const resetPassword = async () => {
  if (!newPassword.value || !confirmPassword.value) {
    uni.showToast({
      title: '请输入新密码',
      icon: 'none'
    });
    return;
  }
  
  if (newPassword.value !== confirmPassword.value) {
    passwordError.value = "两次输入的密码不一致";
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    });
    return;
  }
  
  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: "${NETWORK_CONFIG.API_BASE_URL}/auth/forget-password/reset",
        method: "POST",
        header: { "Content-Type": "application/json" },
        data: resetType.value === 'code' ? {
          identifier: identifier.value,
          newPassword: newPassword.value,
          resetType: 'code',
          code: code.value
        } : {
          identifier: identifier.value,
          newPassword: newPassword.value,
          resetType: 'face',
          frames: recordedFrames.value,
          action: currentAction.value
        },
        success: (res) => {
          resolve({
            ok: res.statusCode >= 200 && res.statusCode < 300,
            statusCode: res.statusCode,
            data: res.data
          });
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
    
    if (response.ok) {
      successMessage.value = "密码重置成功！";
      errorMessage.value = "";
      passwordError.value = "";
      
      uni.showToast({
        title: '密码重置成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/auth/login/index'
        });
      }, 2000);
    } else {
      errorMessage.value = response.data.message || "密码重置失败";
      successMessage.value = "";
      
      uni.showToast({
        title: response.data.message || '密码重置失败',
        icon: 'none'
      });
    }
  } catch (error) {
    errorMessage.value = "重置密码时出错: " + error.message;
    successMessage.value = "";
    
    uni.showToast({
      title: '重置密码失败',
      icon: 'none'
    });
  }
};

const goBack = () => {
  currentStep.value = 1;
  newPassword.value = "";
  confirmPassword.value = "";
  passwordError.value = "";
  errorMessage.value = "";
  successMessage.value = "";
};

const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/auth/login/index'
  });
};

// 监听密码确认
watch([newPassword, confirmPassword], () => {
  if (confirmPassword.value && newPassword.value !== confirmPassword.value) {
    passwordError.value = "两次输入的密码不一致";
  } else {
    passwordError.value = "";
  }
});

onUnmounted(() => {
  stopCamera();
  if (codeTimer) clearInterval(codeTimer);
  if (recordingInterval.value) clearInterval(recordingInterval.value);
  if (frameCaptureInterval.value) clearInterval(frameCaptureInterval.value);
});

onMounted(() => {
  // #ifdef H5
  // 移动端键盘弹出处理
  const handleResize = () => {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
  };
  
  window.addEventListener('resize', handleResize);
  handleResize();
  
  // 防止iOS Safari中的橡皮筋效果
  document.body.addEventListener('touchmove', (e) => {
    if (e.target.closest('.forget-password-card')) {
      e.preventDefault();
    }
  }, { passive: false });
  // #endif
  // 默认获取一次动作（人脸方式时）
  getNewAction();
});

// 获取忘记密码的人脸动作
const getNewAction = async () => {
  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/auth/forget-password/face/action`,
      method: 'GET'
    });
    if (res.statusCode === 200) {
      currentAction.value = res.data.action;
      actionDescription.value = res.data.description;
    } else {
      uni.showToast({ title: (res.data && res.data.message) || '获取动作失败', icon: 'none' });
    }
  } catch (err) {
    uni.showToast({ title: '获取动作失败: ' + err.message, icon: 'none' });
  }
};
</script>

<style scoped>
body, html {
  margin: 0;
  padding: 0;
  width: 100vw;
  overflow-x: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background: #f6f8fa;
}

.forget-password-page {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #667eea;
  padding: 0;
  box-sizing: border-box;
  overflow-x: hidden;
  position: relative;
  z-index: 2;
}

.container {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  box-sizing: border-box;
}

.forget-password-card {
  width: 100%;
  max-width: 450px;
  margin: 0 auto;
  background: #fff;
  border-radius: 20px;
  /* box-shadow: 0 8px 32px rgba(0,0,0,0.1);  // WXSS不支持 */
  padding: 30px 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  /* backdrop-filter: blur(10px); // WXSS不支持 */
  border: 1px solid #eee;
}

.title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 5px;
  text-align: center;
  letter-spacing: -0.5px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 0.95rem;
  color: #4a5568;
  font-weight: 500;
  margin-bottom: 2px;
}

input, select {
  padding: 16px 14px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 1rem;
  outline: none;
  background: #f8fafc;
  font-family: inherit;
}

input:focus, select:focus {
  border: 2px solid #4f8cff;
  background: #fff;
}

.field-error {
  color: #dc2626;
  font-size: 0.85rem;
  margin-top: 4px;
  font-weight: 500;
}

.code-group {
  display: flex;
  gap: 10px;
  align-items: stretch;
}

.code-group input {
  flex: 1;
}

.send-code-btn {
  padding: 16px 20px;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  white-space: nowrap;
  min-width: 100px;
}

.send-code-btn:disabled {
  background: #cbd5e1;
  cursor: not-allowed;
}

.next-btn, .reset-btn {
  width: 100%;
  padding: 18px 0;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 700;
  cursor: pointer;
  margin-top: 10px;
}

.next-btn:disabled, .reset-btn:disabled {
  background: #cbd5e1;
  cursor: not-allowed;
}

.back-btn {
  width: 100%;
  padding: 16px 0;
  background: #f1f5f9;
  color: #64748b;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  margin-top: 8px;
}

.back-btn:active {
  background: #e2e8f0;
}

.links {
  text-align: center;
  margin-top: 15px;
  font-size: 0.9rem;
  line-height: 1.5;
}

.links text {
  color: #4f8cff;
  text-decoration: none;
  margin: 0 8px;
  cursor: pointer;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 6px;
}

.error-message {
  background: #fef2f2;
  color: #dc2626;
  border-radius: 12px;
  padding: 14px 16px;
  font-size: 0.9rem;
  text-align: center;
  border: 1px solid #fecaca;
  font-weight: 500;
}

.success-message {
  background: #f0fdf4;
  color: #16a34a;
  border-radius: 12px;
  padding: 14px 16px;
  font-size: 0.9rem;
  text-align: center;
  border: 1px solid #bbf7d0;
  font-weight: 500;
}

.face-recognition {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
}

.face-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-top: 12px;
  flex-wrap: wrap;
}

.face-buttons button {
  padding: 12px 16px;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  min-width: 80px;
}

.face-buttons button:disabled {
  background: #cbd5e1;
  cursor: not-allowed;
}

.video-container {
  width: 100%;
  max-width: 100%;
  height: 250px;
  background: #000;
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 16px;
}

.face-preview {
  margin-top: 12px;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
  pointer-events: none;
}
.floating-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 1;
}
.floating-shapes > div {
  position: absolute;
  border-radius: 50%;
  background: rgba(255,255,255,0.08);
}
.particle-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
  pointer-events: none;
}
</style>
